package com.aifast.system.sys.service;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.aifast.common.base.BaseEntity;
import com.aifast.common.base.R;
import com.aifast.common.layui.LayuiDataTable;
import com.aifast.common.layui.LayuiPageFactory;
import com.aifast.common.util.AiUtil;
import com.aifast.common.util.EasyExcelUtil;
import com.aifast.system.sys.dao.SysMessageDao;
import com.aifast.system.sys.dao.SysUserDao;
import com.aifast.system.sys.entity.SysMessage;
import com.aifast.system.sys.entity.SysMessageUser;
import com.aifast.system.sys.entity.SysUser;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 站内信Service业务层处理
 *
 * @author fujian
 * @date 2022-10-19
 */
@Service
@RequiredArgsConstructor
public class SysMessageService extends ServiceImpl<SysMessageDao, SysMessage> {
    private final SysMessageDao dao;
    private final SseEmitterService sseEmitterService;
    private final SysUserDao userDao;
    private final SysMessageUserService messageUserService;

    /**
     * layui数据表格列表查询方法
     * <br>这里参数不使用参数类，当超过5个参数时筛选条件参数建议使用参数类param封装
     *
     * @param pg 分页
     * @return 列表数据
     */
    public LayuiDataTable list(Integer type, String message, Page pg) {
        return LayuiPageFactory.init(page(pg, dao.select(type, message)));
    }


    /**
     * 新增或者修改
     * <br> 这里的接口调用一单新增数据就会自动发送消息
     * <br>vo的方法另写，里面有判定是否新增还是修改 可自定义逻辑
     *
     * @param sysMessage
     * @return
     */
    @Transactional
    public Boolean insertOrUpdate(SysMessage sysMessage) {
        if (ObjectUtil.isNull(sysMessage.getId())) {

        }
        boolean saveOrUpdate = saveOrUpdate(sysMessage);
        if (saveOrUpdate) {
            ThreadUtil.execAsync(() -> doSend(sysMessage));
        }
        return saveOrUpdate;
    }

    /**
     * 构造发送消息事件
     * @param message
     */
    private void doSend(SysMessage message) {
        /*发送消息*/
//        Console.log("开始发送消息");
//        Console.log(message);

        String now = DateUtil.now();
        List<SysMessageUser> entityList = new ArrayList<>();
        if (message.getSendType().equals(3)) {
            String[] strings = message.getObjectValue().split(",");
            for (String s : strings) {
                sseEmitterService.send(s, message);
                entityList.add(SysMessageUser.builder().messageId(message.getId()).userId(Convert.toInt(s)).sendTime(now).build());
            }
        } else if (message.getSendType().equals(2)) {
            Integer[] integers = Convert.toIntArray(message.getObjectValue().split(","));
            List<SysUser> users = userDao.selectList(new QueryWrapper<SysUser>().eq("state", 0).in("org_id", integers));
            List<Integer> collect = users.stream().map(BaseEntity::getId).collect(Collectors.toList());
            collect.forEach(i -> {
                sseEmitterService.send(i.toString(), message);
                entityList.add(SysMessageUser.builder().messageId(message.getId()).userId(i).sendTime(now).build());
            });
        }

        messageUserService.batchInsert(entityList);
    }

    /**
     * 删除方法
     * <br>提供单个删除和批量删除
     *
     * @param id  数据id
     * @param ids 数据id集合
     * @return
     */
    public Boolean del(Integer id, String ids) {
        List<Integer> list = new ArrayList<>();
        if (StrUtil.isNotBlank(ids)) {
            list = Convert.toList(Integer.class, ids.split(","));
        }
        if (ObjectUtil.isNotNull(id)) {
            list.add(id);
        }
        try {
            list.forEach(i -> {
                update(new UpdateWrapper<SysMessage>().set("deleted", true).eq("id", i));
            });
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 数据详情
     *
     * @param id 数据id
     * @return
     */
    public R info(Integer id) {
        if (ObjectUtil.isNull(id)) return R.ERROR();
        SysMessage one = getById(id);
        return R.OK(one);
    }

    /**
     * 导出文档功能 该功能与列表页调用接口一致
     *
     * @param response 响应流
     */
    @SneakyThrows
    public void export(Integer type, String message, HttpServletResponse response) {
        Page page = page(AiUtil.getExportPage(), dao.select(type, message));
        EasyExcelUtil.export("站内信", "", SysMessage.class, page.getRecords(), response);
    }



    public LayuiDataTable getRecord(String userId,Integer messageId, String sendTime, String read, Page page) {
        return messageUserService.list(userId, messageId, read, sendTime, page);
    }

    public void read(Integer userId, Integer messageId) {
        List<SysMessageUser> list = messageUserService.list(new QueryWrapper<SysMessageUser>().eq("user_id", userId).eq("message_id", messageId));
        list.forEach(i->i.setIsRead("1"));
        messageUserService.updateBatchById(list);
    }
}
